<template>
  <edit-card :title="title" :type="type" :loading="globalLoading" @confirm="confirmTask">
    <div class="edit-task">
      <a-form
        ref="caseFormRef"
        :model="formState"
        :rules="caseRules"
        :label-col="{ style: { width: '120px' } }"
        class="w-560"
        label-align="left"
      >
        <a-form-item label="案例名称" name="name">
          <a-input v-model:value="formState.name" v-trim class="w-440" placeholder="请输入案例名称" :maxlength="20" />
        </a-form-item>

        <a-form-item label="案例类型" name="caseType">
          <a-radio-group v-model:value="formState.caseType">
            <a-radio value="0">GPT对话</a-radio>
            <a-radio value="2">绘图-MJ模式</a-radio>
            <a-radio value="1">绘图-SD模式</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="相关课程章节" name="courseId">
          <a-select
            v-model:value="formState.courseId"
            class="w-440"
            :field-names="{ label: 'v', value: 'id' }"
            allow-clear
            :show-search="true"
            :filter-option="filterOption"
            :options="onlineOptions"
            placeholder="请选择相关课程章节"
            style="width: 100%"
          />
          <!-- @search="getDataLabel({ type: 'chapters',name: })" -->
        </a-form-item>
        <a-form-item label="学习预估耗时" name="time">
          <a-input v-model:value="formState.time" v-trim class="w-440" placeholder="请输入学习预估耗时" :maxlength="3" suffix="分钟" />
        </a-form-item>
        <a-form-item label="案例文件" name="url">
          <file-upload
            v-model:file-url="formState.url"
            class="file-upload w-440"
            :max-count="1"
            :is-preview="true"
            accept="pdf,docx,doc"
            suffix="pdf,docx,doc"
            :max-file-size="20"
            :module-prefix="'proj'"
          >
            <a-button
              type="dashed"
              size="small"
              class="icon-with-btn btn-mini"
              :disabled="!checkKey(['admin-case-manage-create', 'admin-case-manage-edit'])"
            >
              <i class="iconfont icon-upload-line"></i>
              上传
            </a-button>
          </file-upload>
          <span class="text-gray-500 text-12px">仅支持上传单个.pdf、.word格式文件 ，且文件大小≤20MB</span>
        </a-form-item>

        <a-form-item label="案例简介" name="description">
          <a-textarea
            v-model:value="formState.description"
            v-trim
            class="w-440"
            placeholder="请输入案例简介"
            :rows="5"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="适学班级" name="organizationIds">
          <a-form-item-rest>
            <g-select-tree-data
              ref="selectDataBucketRef"
              v-model:checkedIds="formState.organizationIds"
              :has-collect="false"
              type-name="选择班级"
              :has-modal="false"
              :node-icon="{ folder: 'icon-group-line', file: 'icon-user-line' }"
              select-data-type="file"
              :get-tree-data-api="learningCaseManageApi.orgAuthTree"
              :get-list-data-api="learningCaseManageApi.orgAuthTreeSearch"
              :field-names="{ children: 'children', title: 'name', key: 'id' }"
            >
              <template #resultTotal="{ fileNum }"> {{ fileNum }}个组织 </template></g-select-tree-data
            >
          </a-form-item-rest>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed, onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import FileUpload from '@/components/upload/FileUpload/index.vue'
  import { checkKey } from '@/directives/auth'
  import { adminCaseManageApi, learningCaseManageApi, schoolOrganizationManageApi, tagManageApi } from '@/services/api'
  import { countStrToBit, validateDirName } from '@/utils'
  import { regex } from '@/utils/regex'

  import { CaseDetailsType, Form, ProjectLabelInfoVO } from '../types'

  const route = useRoute()

  const router = useRouter()
  const caseFormRef = ref()

  const caseId = route.params.id as string | ''

  const formState = ref<Form>({
    name: '',
    description: '',
    caseType: '0',
    courseId: null,
    url: '',
    organizationIds: [],
    time: ''
  })
  const detailData = ref<CaseDetailsType>({})

  let onlineOptions = ref<DictionaryVOResponse[]>([])

  /**
   * DictionaryVO
   */
  interface DictionaryVOResponse {
    /**
     * 主动创建时间
     */
    createTime?: string
    /**
     * 主键id
     */
    id?: number
    /**
     * 存储值，例如：1、2、3...
     */
    k?: number
    /**
     * 父id，例如：二级联动
     */
    pid?: number
    /**
     * 备注
     */
    remark?: string
    /**
     * 排序值
     */
    sort?: number
    /**
     * 字典类型，例如：个性标签、服务类型...
     */
    type?: string
    /**
     * 被动更新时间
     */
    updateTime?: string
    /**
     * 显示值，例如：创建中、完成...
     */
    v?: string
    [property: string]: any
  }

  const { runAsync: getDataLabel } = useRequest<ResponseData<DictionaryVOResponse[]>>(tagManageApi.list, {
    onSuccess: res => {
      for (let item of res.data) {
        if (item.type === 'chapters') {
          onlineOptions.value.push(item)
        }
      }
    }
  })
  getDataLabel({ type: 'chapters' })

  const type = ref((caseId ? 'edit' : 'add') as 'edit' | 'add')

  const title = computed(() => {
    return caseId ? `编辑案例（${detailData.value.name || ''}）` : '创建案例'
  })
  const validateByte = async (rule: Rule, value: string) => {
    const byteCount = countStrToBit(value)
    if (byteCount === 0) {
      return Promise.reject('请输入案例名称')
    } else if (byteCount > 200) {
      return Promise.reject('名称不可超过200字节')
    }
    return Promise.resolve()
  }

  // const organizationIds = ref<string[]>([{
  // 	name: '23ed3',
  // 		id
  // 	}])
  const caseRules: Record<string, Rule[]> = {
    name: [
      { validator: validateDirName() },
      { required: true, trigger: 'change', validator: validateByte },
      {
        pattern: regex.CHENNumber,
        message: '仅支持中英文、数字'
      }
    ],

    caseType: [
      {
        required: true,
        message: '请选择类别'
      }
    ],
    time: [
      {
        pattern: /^[1-9][0-9]{0,2}$/,
        message: '仅支持3位内的正整数'
      }
    ],
    courseId: [
      {
        required: true,
        message: '请选择课程章节'
      }
    ],
    description: [
      {
        required: true,
        message: '请输入案例简介'
      }
    ],
    url: [{ required: true, message: '请上传案例文件', trigger: 'change' }],
    organizationIds: [{ required: true, message: '请选择班级', trigger: 'change' }]
  }

  //全局Loading
  const globalLoading = computed(() => {
    return getDetailLoading.value || addLoading.value || updateLoading.value
  })

  const filterOption = (input: string, option: any) => {
    return option.v.toLowerCase().includes(input.toLowerCase())
  }

  // TODO:确定
  const confirmTask = () => {
    caseFormRef.value
      .validate()
      .then(() => {
        submitForm()
      })
      .catch((err: any) => {
        console.log(err)
      })
  }
  //新增
  const { loading: addLoading, runAsync: runAddAsync } = useRequest(learningCaseManageApi.add)
  //修改
  const { loading: updateLoading, runAsync: runUpdateAsync } = useRequest(learningCaseManageApi.edit)

  //点击确定
  const submitForm = async () => {
    formState.value.courseId = formState.value.courseId || ''
    const params = { ...formState.value }
    const isAdd = type.value === 'add'
    console.log(params, 'params')

    try {
      await (isAdd ? runAddAsync(params, { isAddUid: true }) : runUpdateAsync({ ...params, id: caseId }, { isAddUid: true }))
      message.success('操作成功')
      goBack()
    } catch (error) {
      console.log(error)
    }
  }
  const goBack = () => {
    router.go(-1)
  }

  const selectDataBucketRef = ref()
  // const getDetailLoading = ref<bole>
  //获取详情数据
  const { loading: getDetailLoading, runAsync: runGetCaseDetail } = useRequest<ResponseData<CaseDetailsType>>(
    (id: string) => learningCaseManageApi.getDetail(id)(),
    {
      onSuccess: ({ data }) => {
        getDetailLoading.value = true
        Object.assign(detailData.value, data)
        Object.assign(formState.value, data, {
          projectLabelIds: data.projectLabelInfoVOS ? data.projectLabelInfoVOS.map((item: ProjectLabelInfoVO) => item.labelId) : []
        })
        detailData.value.orgInfoVos?.forEach(it => {
          selectDataBucketRef.value?.addKey({
            key: it.id,
            title: it.name,
            isLeaf: false
          })
        })
        formState.value.organizationIds = detailData.value?.orgInfoVos?.map(item => {
          return item.id
        })
        // delete formState.value.updateTime
        Reflect.deleteProperty(formState.value, 'updateTime')
        console.log(formState.value, 'formState')
        getDetailLoading.value = false
      }
    }
  )
  const getDetailData = (id: string) => {
    runGetCaseDetail(id)
  }
  onMounted(async () => {
    type.value === 'edit' && getDetailData(caseId)
  })
</script>
<style lang="less" scoped>
  .edit-task {
    :deep(.ant-form-item) {
      margin-bottom: 40px;
    }

    :deep(.ant-form-item-label > label::after) {
      display: none;
    }

    :deep(.ant-radio-wrapper) {
      margin-right: 24px;
    }

    .ant-radio-wrapper :deep(.ant-transfer-list) {
      position: relative;

      .ant-transfer-list-header {
        height: 39px;
        background: #fafafa;
      }

      &:first-child {
        .ant-transfer-list-header {
          &::after {
            content: '待选';
            position: absolute;
            right: 8px;
          }
        }
      }

      &:last-child {
        .ant-transfer-list-header {
          &::after {
            content: '已选';
            position: absolute;
            right: 8px;
          }
        }
      }

      .ant-input-affix-wrapper {
        height: 32px;
        min-height: 32px !important;
      }
    }

    .tag-select {
      display: flex;

      .left {
        margin-right: 80px;
      }
    }
  }
</style>
